package com.vrv.app.cyberspace.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.vrv.app.cyberspace.common.ddio.ApiV2Service;
import com.vrv.app.cyberspace.common.ddio.DDIORunnable;
import com.vrv.app.cyberspace.common.ddio.TemplateMessage;
import com.vrv.app.cyberspace.common.utils.HttpContextUtils;
import com.vrv.app.cyberspace.common.utils.JSONResult;
import com.vrv.app.cyberspace.config.WXBSystemConfig;
import com.vrv.app.cyberspace.modules.sys.entity.*;
import com.vrv.app.cyberspace.modules.sys.mapper.*;
import com.vrv.app.cyberspace.modules.sys.service.IEventApprovalTableService;
import com.vrv.app.cyberspace.modules.sys.service.IEventManageTableService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.vrv.app.cyberspace.common.utils.JSONResult.renderError;
import static com.vrv.app.cyberspace.common.utils.JSONResult.renderSuccess;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sm
 * @since 2018-01-18
 */
@SuppressWarnings({"SpringJavaInjectionPointsAutowiringInspection", "Duplicates"})
@Service
@Transactional
public class EventManageTableServiceImpl extends ServiceImpl<EventManageTableMapper, EventManageTable> implements IEventManageTableService {
    Logger logger = LoggerFactory.getLogger(RiskTableServiceImpl.class);

    @Autowired
    private EventManageTableMapper eventManageTableMapper;
    @Autowired
    private RoleTableMapper roleTableMapper;
    @Autowired
    private BaseTableMapper baseTableMapper;
    @Autowired
    private UserTableMapper userTableMapper;
    @Autowired
    private InfrastructureInformationTableMapper infrastructureInformationTableMapper;
    @Autowired
    private EventTypeTableMapper eventTypeTableMapper;
    @Autowired
    private AttachmentTableMapper attachmentTableMapper;
    @Autowired
    private IndustryTableMapper industryTableMapper;
    @Autowired
    private RegionTableMapper regionTableMapper;
    @Autowired
    private EventApprovalTableMapper eventApprovalTableMapper;
    @Autowired
    private EventFeedbackTableMapper eventFeedbackTableMapper;
    @Autowired
    private IEventApprovalTableService eventApprovalTableService;
    @Autowired
    private ApiV2Service apiV2Service;
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    @Autowired
    private WXBSystemConfig wxbSystemConfig;

    @Override
    public JSONResult addToEventManage(Integer id, EventManageTable emt, String infrastructure_information, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        BaseTable baseTable = baseTableMapper.selectById(id);
        UserTable approvalUser = userTableMapper.selectById(emt.getApprovalUserID());
        RoleTable approvalUserRole = roleTableMapper.selectById(approvalUser.getRoleID());
        if (!roleTable.getRoleRank().equals("2")) {
            if (approvalUserRole.getRoleRank().equals("6")) {
                return renderError("操作被禁止，只有值班员才能进行研判！");
            }
        }
        if (baseTable == null) {
            return renderError("操作被禁止，此条记录不存在！");
        }
        if (baseTable.getIsEventManage() == 1) {
            return renderError("操作被禁止，此条记录已进行过事件通知！");
        }
        baseTable.setIsEventManage(1);
        baseTable.updateById();
        emt.setBaseID(id);
        emt.setReportUserID(baseTable.getCreateUserID());
        emt.setStatus(2);
        emt.setCreateUserID(userTable.getLinkdoodID());
        List<InfrastructureInformationTable> iits = JSONArray.parseArray(infrastructure_information, InfrastructureInformationTable.class);
        List<Integer> infrastructureIDs = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(iits)) {
            for (InfrastructureInformationTable iit :
                    iits) {
                infrastructureInformationTableMapper.insert(iit);
                infrastructureIDs.add(iit.getId());
            }
        }
        emt.setInfrastructureIDs(StringUtils.join(infrastructureIDs, ","));
        Date now = new Date();
        emt.setCreateTime(now);
        emt.setUpdateTime(now);
        List<Integer> attIDs = new ArrayList<>();
        if (StringUtils.isNotEmpty(emt.getEnclosure())) {
            try {
                JSONArray upLoadFiles = JSONArray.parseArray(emt.getEnclosure());
                for (Object upLoadFile :
                        upLoadFiles) {
                    AttachmentTable attachmentTable = new AttachmentTable();
                    attachmentTable.setName(upLoadFile.toString().substring(upLoadFile.toString().lastIndexOf("/") + 1));
                    attachmentTable.setUrl(upLoadFile.toString());
                    attachmentTable.insert();
                    attIDs.add(attachmentTable.getId());
                }
            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return renderError("附件参数格式异常！");
            }
            emt.setEnclosure(StringUtils.join(attIDs, ","));
        }
        emt.insert();
        //如果请示人为专家状态则为2专家研判，否则为1请示领导
        EventApprovalTable eat = new EventApprovalTable();
        eat.setBaseID(emt.getBaseID());
        eat.setUserID(userTable.getLinkdoodID());
        eat.setAdvice(advice);
        if (approvalUserRole.getRoleRank().equals("6")) {
            eat.setApprovalStatue(2);
        } else {
            eat.setApprovalStatue(1);
        }
        eat.setCreateTime(now);
        eat.insert();
        logger.info("新增事件管理" + emt.getBaseID() + "由" + userTable.getLinkdoodID() + "-" + userTable.getLinkdoodName() + "新增");
        pushTemplateMessage(emt, emt.getApprovalUserID(), eventTypeTableMapper.selectById(emt.getPrimaryEventTypeFirst()).getName());
        return renderSuccess();
    }

    @Override
    public JSONResult getListEventManage(Page<EventManageTable> page, String startTime, String endTime, String eventLevel, String eventType, Integer timeType, Integer status, String title) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        EntityWrapper<EventManageTable> ew = new EntityWrapper<>();
        if (status != null) {
            if (status == 1) {
                ew.and("status!=7");
                ew.orderBy("approvalUserID != " + userTable.getLinkdoodID() + ",updateTime", false);
            } else if (status == 2) {
                ew.eq("status", 7);
                ew.orderBy("updateTime", false);
            }
        }
        if (timeType!=null){
            String timeTypeString = timeType==1?"createTime":"updateTime";
            if (StringUtils.isNotEmpty(startTime)&&StringUtils.isNotEmpty(endTime)){
                ew.between(timeTypeString,startTime+" 00:00:00",endTime+" 23:59:59");
            }else if (StringUtils.isNotEmpty(startTime)&&StringUtils.isEmpty(endTime)){
                ew.and(timeTypeString+">={0}",startTime);
            }else if (StringUtils.isEmpty(startTime)&&StringUtils.isNotEmpty(endTime)){
                ew.and(timeTypeString+"<={0}",endTime);
            }
        }
        if (StringUtils.isNotEmpty(title)) {
            ew.like("title", title);
        }
        if (StringUtils.isNotEmpty(eventLevel)) {
            ew.in("primaryEventGrade", eventLevel.split(","));
        }
        if (StringUtils.isNotEmpty(eventType)) {
            ew.in("primaryEventTypeFirst", eventType.split(","));
        }
        ew.and("(createUserID = {0} or approvalUserID = {0} or baseID in (select baseID from EVENT_APPROVAL_TABLE where userID = {0}))", userTable.getLinkdoodID());
        List<EventManageTable> emts = eventManageTableMapper.selectPage(page, ew);
        for (EventManageTable emt : emts) {
            emt.setCreateUserInfo(userTableMapper.selectById(emt.getCreateUserID()));
            emt.setApprovalUserInfo(userTableMapper.selectById(emt.getApprovalUserID()));
            emt.setFirstEventType(eventTypeTableMapper.selectById(emt.getPrimaryEventTypeFirst()));
            emt.setSecondEventType(eventTypeTableMapper.selectById(emt.getPrimaryEventTypeSecond()));
        }
        page.setRecords(emts);
        return renderSuccess(page);
    }

    @Override
    public JSONResult getEventManage(Integer id) {
        EventManageTable emt = getEventExtend(id);
        if (emt == null) {
            return renderError("信息不存在！");
        }
        return renderSuccess(emt);
    }

    @Override
    public EventManageTable getEventExtend(Integer id) {
        EventManageTable emt = eventManageTableMapper.selectById(id);
        if (emt != null) {
            emt.setCreateUserInfo(userTableMapper.selectById(emt.getCreateUserID()));
            emt.setApprovalUserInfo(userTableMapper.selectById(emt.getApprovalUserID()));
            String[] appendixAttIDs = StringUtils.isNotEmpty(emt.getAppendix()) ? emt.getAppendix().split(",") : new String[0];
            List<AttachmentTable> appendixAttList = new ArrayList<>();
            for (String appendixAttID : appendixAttIDs) {
                appendixAttList.add(attachmentTableMapper.selectById(appendixAttID));
            }
            emt.setAppendixList(appendixAttList);
            String[] attIDs = StringUtils.isNotEmpty(emt.getEnclosure()) ? emt.getEnclosure().split(",") : new String[0];
            List<AttachmentTable> attachmentList = new ArrayList<>();
            for (String attID : attIDs) {
                attachmentList.add(attachmentTableMapper.selectById(attID));
            }
            emt.setAttachmentList(attachmentList);
            emt.setFirstEventType(eventTypeTableMapper.selectById(emt.getPrimaryEventTypeFirst()));
            emt.setSecondEventType(eventTypeTableMapper.selectById(emt.getPrimaryEventTypeSecond()));
            List<IndustryTable> industryList = industryTableMapper.selectList(new EntityWrapper<IndustryTable>().in("id", emt.getIndustryIDs().split(",")));
            if (CollectionUtils.isNotEmpty(industryList)) {
                List<String> industryListString = new ArrayList<>();
                for (IndustryTable it : industryList) {
                    industryListString.add(it.getName());
                }
                emt.setIndustryListString(StringUtils.join(industryListString, ","));
            }
            emt.setIndustryList(industryList);
            List<RegionTable> regionList = regionTableMapper.selectList(new EntityWrapper<RegionTable>().in("id", emt.getRegionIDs().split(",")));
            if (CollectionUtils.isNotEmpty(regionList)) {
                List<String> regionListString = new ArrayList<>();
                for (RegionTable rrt : regionList) {
                    regionListString.add(rrt.getName());
                }
                emt.setRegionListString(StringUtils.join(regionListString, ","));
            }
            emt.setRegionList(regionList);
            if (StringUtils.isNotEmpty(emt.getInfrastructureIDs())) {
                List<InfrastructureInformationTable> iits = new ArrayList<>();
                for (String InfrastructureInformationID : emt.getInfrastructureIDs().split(",")) {
                    InfrastructureInformationTable iit = infrastructureInformationTableMapper.selectById(InfrastructureInformationID);
                    iits.add(iit);
                }
                emt.setInfrastructureList(iits);
            }
            List<EventApprovalTable> eventApprovalList = eventApprovalTableMapper.selectList(new EntityWrapper<EventApprovalTable>().eq("baseID", id));
            for (EventApprovalTable eat : eventApprovalList) {
                eat.setUserInfo(userTableMapper.selectById(eat.getUserID()));
            }
            emt.setApprovalList(eventApprovalList);
            getFeedbackNum(emt, emt.getDownsSet());
            getManufacturers(emt, emt.getManufacturers());
        }
        return emt;
    }

    @Override
    public JSONResult releaseEvent(EventManageTable emt) {
        try {
            List<String> orgIDs = JSONArray.parseArray(emt.getDownsSet(), String.class);
            List<String> safeOrgIDS = JSONArray.parseArray(emt.getManufacturers(), String.class);
            //1.根据OrgID查询组织下的人员
            List<String> all = orgIDs;
            if (!org.springframework.util.CollectionUtils.isEmpty(safeOrgIDS))
                all.addAll(safeOrgIDS);
            List<UserTable> list = userTableMapper.selectList(new EntityWrapper<UserTable>().in("orgID", all));
            //2.创建反馈表
            EventFeedbackTable eventFeedback = new EventFeedbackTable();
            eventFeedback.setBaseID(emt.getBaseID());
            eventFeedback.setCreateTime(new Date());
            for (String orgid : all) {
                eventFeedback.setOrgID(orgid);
                eventFeedbackTableMapper.insert(eventFeedback.clone());
            }
            //4.记录下发厂商/应对要求/处置要求
            emt.setReplyClaim(emt.getReplyClaim());//应对要求
            emt.setHandleClaim(emt.getHandleClaim());//处置要求
            emt.setManufacturers(emt.getManufacturers());//下发的安全厂商
            //5.记录下发单位
            emt.setDownsSet(emt.getDownsSet());
            eventManageTableMapper.updateById(emt);
            // TODO: 2018/1/16
            eventApprovalTableService.releaseEventApproval(emt.getBaseID(), "值班员下发");
            //6.推送模板消息
            Set<String> toUsers = new HashSet<>();
            for (UserTable u : list) {
                toUsers.add(u.getLinkdoodID());
            }
            pushTemplateMessage(emt, new ArrayList<>(toUsers));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return renderSuccess();
    }

    @Override
    public JSONResult getListProfessorEvent(Page<EventManageTable> page, Integer status) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        if (!roleTableMapper.selectById(userTable.getRoleID()).getRoleRank().equals("6")) {
            return renderError("操作被禁止，当前用户不是专家！");
        }
        EntityWrapper<EventManageTable> ew = new EntityWrapper<>();
        if (status == 0) {
            ew.and("status!=7");
            ew.and("approvalUserID = {0}", userTable.getLinkdoodID());
        }
        if (status == 1) {
            ew.and("status!=7");
            ew.and("baseID in (select baseID from EVENT_APPROVAL_TABLE where userID = {0})", userTable.getLinkdoodID());
            ew.and("approvalUserID != {0}", userTable.getLinkdoodID());
        }
        if (status == 2) {
            ew.and("baseID in (select baseID from EVENT_APPROVAL_TABLE where userID = {0})", userTable.getLinkdoodID());
            ew.eq("status", 7);
        }
        ew.orderBy("updateTime", false);
        List<EventManageTable> emts = eventManageTableMapper.selectPage(page, ew);
        for (EventManageTable emt : emts) {
            emt.setCreateUserInfo(userTableMapper.selectById(emt.getCreateUserID()));
            emt.setApprovalUserInfo(userTableMapper.selectById(emt.getApprovalUserID()));
            emt.setFirstEventType(eventTypeTableMapper.selectById(emt.getPrimaryEventTypeFirst()));
            emt.setSecondEventType(eventTypeTableMapper.selectById(emt.getPrimaryEventTypeSecond()));
        }
        page.setRecords(emts);
        return renderSuccess(page);
    }

    private void getFeedbackNum(EventManageTable emt, String downSet) {
        //4.共下发多少家,反馈/未反馈数据量
        List<String> list = JSON.parseArray(downSet, String.class);
        if (list != null && list.size() > 0) {
            emt.setTotalNum(list.size());
            emt.setFeedbackNum(eventFeedbackTableMapper.selectCount(new EntityWrapper<EventFeedbackTable>()
                    .eq("baseID", emt.getBaseID())
                    .in("orgID", list)
                    .in("status", new Integer[]{1, 2})));
        }
    }

    private void getManufacturers(EventManageTable emt, String manufacturers) {
        //5.安全厂商共下发了多少家, 反馈/未反馈数据量
        List<String> list = JSON.parseArray(manufacturers, String.class);
        if (list != null && list.size() > 0) {
            emt.setTotalManuf(list.size());
            emt.setHadSubmit(eventFeedbackTableMapper.selectCount(new EntityWrapper<EventFeedbackTable>()
                    .eq("baseID", emt.getBaseID())
                    .in("orgID", list)
                    .in("status", new Integer[]{1, 2})));
        }
    }

    private void pushTemplateMessage(EventManageTable emt, String toUsers, String type) {
        String appid = apiV2Service.getAppID();
        String content = "时间: " + dateFormat.format(new Date()) + "\n标题：" + emt.getTitle() + "\n类别: " + type + "\n请您及时处理 ";
        TemplateMessage templateMessage = TemplateMessage.createOne(appid, "事件管理", appid, content, wxbSystemConfig.getEventFeedbackDetailUrl() + "&id=" + emt.getBaseID(),
                toUsers);
        try {
            executorService.execute(new DDIORunnable(apiV2Service, "sendTemplateMsg", templateMessage, TemplateMessage.class));
        } catch (NoSuchMethodException e) {
            logger.info("推送事件管理" + "(ID" + emt.getBaseID() + ")消息失败! ");
            e.printStackTrace();
        }
    }

    private void pushTemplateMessage(EventManageTable emt, List<String> toUsers) {
        String appid = apiV2Service.getAppID();
        emt=eventManageTableMapper.selectById(emt.getBaseID());
        EventTypeTable firstEventType = eventTypeTableMapper.selectById(emt.getPrimaryEventTypeFirst());
        EventTypeTable secondEventType = eventTypeTableMapper.selectById(emt.getPrimaryEventTypeSecond());
        String content = "时间: " + dateFormat.format(new Date()) + "\n标题：" + emt.getTitle() + "\n类别: " + firstEventType.getName() + "-" + secondEventType.getName() + "\n请您及时处理 ";
        TemplateMessage templateMessage = TemplateMessage.createOne(appid, "事件管理", appid, content, wxbSystemConfig.getEventFeedbackDetailUrl() + "&id=" + emt.getBaseID(),
                StringUtils.join(toUsers.toArray(), ','));
        try {
            executorService.execute(new DDIORunnable(apiV2Service, "sendTemplateMsg", templateMessage, TemplateMessage.class));
        } catch (NoSuchMethodException e) {
            logger.info("推送事件管理(ID" + emt.getBaseID() + ")消息失败! ");
            e.printStackTrace();
        }
    }
}
